package pers.spj.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

import androidx.collection.backup.LruCache;

/**
 * @author supeijin
 */
public class ServiceManager {
    private static class ManagerHolder {
        private static LruCache<String, Object> mLruCache = new LruCache<>(20);
        private static ServiceManager mServiceManager = new ServiceManager();
    }

    private ServiceManager() {
    }

    public static ServiceManager getInstance() {
        return ManagerHolder.mServiceManager;
    }

    public <T> T getService(Class<T> cls,boolean useCache) {
        String name = cls.getName();
        if(useCache){
            final Object serviceObject = ManagerHolder.mLruCache.get(name);
            if (serviceObject != null) {
                return (T) serviceObject;
            }
        }
        List<T> services = getServicesFromClass(cls, false);
        if (services.size() > 0) {
            T service = services.get(0);
            if(useCache){
                ManagerHolder.mLruCache.put(name, service);
            }
            return service;
        }
        return null;
    }

    public <T> List<T> getAllServices(Class<T> cls) {
        return getServicesFromClass(cls, true);
    }

    public void release() {
        ManagerHolder.mLruCache.evictAll();
    }

    private <T> List<T> getServicesFromClass(Class<T> cls, boolean all) {
        ArrayList<T> arrayList = new ArrayList<>();
        ServiceLoader<T> serviceLoader = ServiceLoader.load(cls, cls.getClassLoader());
        Iterator<T> iterator = serviceLoader.iterator();
        while (iterator.hasNext()) {
            arrayList.add(iterator.next());
            if (!all) {
                break;
            }
        }
        return arrayList;
    }
}
